package edu.hut.bookshop.controller;

import com.github.pagehelper.PageInfo;
import edu.hut.bookshop.pojo.Order;
import edu.hut.bookshop.pojo.User;
import edu.hut.bookshop.service.OrderHandleService;
import edu.hut.bookshop.service.OrderService;
import edu.hut.bookshop.util.ResultCode;
import edu.hut.bookshop.util.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户中心模块
 */
@Controller
@RequestMapping("/user_center")
public class UserCenterController {

    @Autowired
    private OrderHandleService orderHandleService;

    @Autowired
    private OrderService orderService;



    /**
     * 根据用户ID,获取用户订单
     * @return
     */
    @GetMapping("/orders")
    @ResponseBody
    public ResultVO getUserOrders(Integer page,Integer limit,HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Order> orders1 = new ArrayList<>();
        List<Order> orders = orderHandleService.getOrdersByUserId(user.getUserId(), page, limit);
        for(int i=0;i<orders.size();i++){
            if(orders.get(i).getIsDelete()==0){
               orders1.add(orders.get(i));
            }
        }
        System.out.println("dd为"+orders.size());
        PageInfo pageInfo = new PageInfo(orders);
        return new ResultVO(ResultCode.SUCCESS, (int)pageInfo.getTotal(),orders1);
    }

    /**
     * 删除指定orderId的订单
     * @param orderId
     * @return
     */
    @DeleteMapping("/orders/{orderId}")
    @ResponseBody
    public ResultVO deleteOrder(@PathVariable("orderId") Integer orderId) {
        int orders;
        //根据发货状态进行决定，未发货就进行物理删除，已发货就进行逻辑删除
        boolean status = orderService.selectByOrderId(orderId).getStatus();
        if(status){//已发货，进行逻辑删除
            orders = orderService.updateisdelete(orderId);
        }else
             orders = orderHandleService.deleteOrderById(orderId);
        return new ResultVO(ResultCode.SUCCESS,null);
    }

    /**
     * 支付成功返回用户支付界面
     * @return
     */
    @GetMapping("/pay")
    public String fhym(HttpSession session){
        User user = (User) session.getAttribute("user");
        String name = user.getUserName();
        return "/pay";
    }

}
